package com.group3.service.impl;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.group3.dao.*;
import com.group3.domain.*;
import com.group3.pojo.DropStudent;
import com.group3.pojo.receive.ReplyWorkReceive;
import com.group3.pojo.receive.TAddWorkReceive;
import com.group3.pojo.receive.TStudentWorkReceive;
//import com.group3.pojo.StudentWork;
import com.group3.pojo.result.StudentWorkResult;
import com.group3.service.ListService;
import com.group3.service.TeacherWorkManageService;
import com.group3.utils.JWTUtils;
import com.group3.utils.NotNull;
import com.group3.utils.Result;
import com.group3.utils.ResultUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static java.lang.Integer.parseInt;

/**
 * TeacherWorkManageServiceImpl
 *
 * @author MHH
 * 2021/06/10 16:49
 **/

@Service
public class TeacherWorkManageServiceImpl implements TeacherWorkManageService {
    @Resource
    private WorkMapper workMapper;
    @Resource
    private LessonTeacherMapper lessonTeacherMapper;
    @Resource
    private GroupMapper groupMapper;
    @Resource
    private StudentWorkMapper studentWorkMapper;
    @Resource
    private ListService listService;
    @Resource
    private StudentGroupMapper studentGroupMapper;


    @Override
    public Result selectStudentWork(TStudentWorkReceive tStudentWorkReceive, String token) {
        DecodedJWT jwt = JWTUtils.getToken(token);//获取token
        String teacherId = jwt.getClaim("id").asString();//操作用户Id

        //查询老师所教课程集合
        LessonTeacherExample lessonTeacherExampleTemp = new LessonTeacherExample();
        lessonTeacherExampleTemp.createCriteria().andTeacherIdEqualTo(teacherId);
        List<LessonTeacherKey> keys = lessonTeacherMapper.selectByExample(lessonTeacherExampleTemp);

        List<String> lessonNameByT = new ArrayList<>();
        for (LessonTeacherKey key : keys) {
            lessonNameByT.add(key.getLessonName());
        }

//        1.new一个对应的example
        WorkExample example = new WorkExample();
        WorkExample.Criteria criteria = example.createCriteria();

        //2.为example添加查询条件
        //发布时间
        if (NotNull.judge(tStudentWorkReceive.getReleaseStartTime())
                && NotNull.judge(tStudentWorkReceive.getReleaseEndTime())) {
            criteria.andReleaseTimeBetween(tStudentWorkReceive.getReleaseStartTime(),
                    tStudentWorkReceive.getReleaseEndTime());
        }
        //项目名称
        if (NotNull.judge(tStudentWorkReceive.getLessonName())) {
            criteria.andLessonNameIn(lessonNameByT);
        }
        //作业主题
        if (NotNull.judge(tStudentWorkReceive.getWorkTheme())) {
            criteria.andWorkThemeEqualTo(tStudentWorkReceive.getWorkTheme());
        }


        // 实训老师
        // 先根据老师查询该老师所教授课程集合，再判断目前课程是否再这个集合中，可实现课程与实训老师的联合查询
        // 根据实训老师查询课程（lesson_teacher表）
        LessonTeacherExample lessonTeacherExample = new LessonTeacherExample();
        lessonTeacherExample.setDistinct(true);
        // 得到一个课程集合
        List<LessonTeacherKey> lessonTeacherKeys;
        lessonTeacherKeys = lessonTeacherMapper.selectByExample(lessonTeacherExample);
        // 取出课程名集合
        List<String> lessonName = new ArrayList<>();
        for (LessonTeacherKey lessonTeacherKey : lessonTeacherKeys) {
            lessonName.add(lessonTeacherKey.getLessonName());
        }
        // 添加集合条件
        criteria.andLessonNameIn(lessonName);

        //计划完成时间
        if (NotNull.judge(tStudentWorkReceive.getCompletionStartTime())
                && NotNull.judge(tStudentWorkReceive.getCompletionEndTime())) {
            criteria.andCompletionTimeBetween(tStudentWorkReceive.getCompletionStartTime(),
                    tStudentWorkReceive.getCompletionEndTime());
        }


        //小组  todo 小组查询还没实现
        // 根据课程查询课程下小组集合,再判断小组是否在这个集合中
        GroupExample groupExample = new GroupExample();
        groupExample.setDistinct(true);
        // 得到一个小组集合
        List<Group> groups;
        groups = groupMapper.selectByExample(groupExample);
        // 取出小组名集合
        List<String> groupName = new ArrayList<>();
        for (Group group : groups) {
            groupName.add(group.getGroupName());
        }
        // 添加集合条件
        criteria.andLessonNameIn(lessonName);

        //作业类型
        if (NotNull.judge(tStudentWorkReceive.getType())) {
            criteria.andTypeEqualTo(tStudentWorkReceive.getType());
        }


//        1.先开启分页
        PageHelper.startPage(tStudentWorkReceive.getPageNumber(), tStudentWorkReceive.getPageSize());

//        2.执行SQL语句selectWorkInfo
        List<StudentWorkResult> studentWorkResults = workMapper.selectWorkInfo(example);

//        3.获取分页信息
        PageInfo<StudentWorkResult> lessonResultPageInfo = new PageInfo<>(studentWorkResults);

        return ResultUtil.success("查询成功", studentWorkResults, lessonResultPageInfo.getTotal());
    }

    @Override
    public Result addWork(TAddWorkReceive tAddWorkReceive) {
        Work work = new Work();

        // 发布时间
        Date date = new Date();
        work.setReleaseTime(date);

        // 作业主题
        work.setWorkTheme(tAddWorkReceive.getWorkTheme());

        // 内容
        work.setWorkContent(tAddWorkReceive.getContent());

        // 计划完成时间
        work.setCompletionTime(tAddWorkReceive.getCompletionTime());

        // 课程
        work.setLessonName(tAddWorkReceive.getLessonName());

        // 发布老师id
        work.setTeacherId(tAddWorkReceive.getTeacherId());

        // 类型
        work.setType(tAddWorkReceive.getType());

//       插入work表记录
        int res = workMapper.insert(work);
        System.out.println("插入workId" + work.getWorkId());

        int type = tAddWorkReceive.getType();
        List<String> students = tAddWorkReceive.getStudents();

        StudentWork studentWork = new StudentWork();
        studentWork.setWorkId(work.getWorkId());

        //日常作业为个人作业,students为学生id
        if (type == 0) {
            for (String studentId : students) {
                studentWork.setStudentId(studentId);
                int stuRes = studentWorkMapper.insert(studentWork);
                if (stuRes < 1) {
                    return ResultUtil.error("为学生生成作业时失败");
                }
            }
        }

        //阶段与最终作业为小组作业,students为小组id
        if (type == 1 || type == 2) {
            List<Integer> groupIdList = new ArrayList<>();
            for (String group : students) {
                groupIdList.add(parseInt(group));
            }

            //通过小组找到学生集合
            StudentGroupExample example = new StudentGroupExample();
            example.createCriteria().andGroupIdIn(groupIdList);
            List<StudentGroupKey> studentGroupKey = studentGroupMapper.selectByExample(example);

            //取出学生id,给每各个学生添加作业记录
            for (StudentGroupKey key : studentGroupKey) {
                studentWork.setStudentId(key.getStudentId());
                int stuRes = studentWorkMapper.insert(studentWork);
                if (stuRes < 1) {
                    return ResultUtil.error("为学生生成作业时失败");
                }
            }
        }
        return ResultUtil.success("插入成功", res);
    }

    @Override
    public Result showWork(Integer workId) {
        WorkExample example = new WorkExample();
        WorkExample.Criteria criteria = example.createCriteria();

        if (NotNull.judge(workId)) {
            criteria.andWorkIdEqualTo(workId);
        }

        return ResultUtil.success("查询成功", workMapper.selectByExample(example));
    }

    @Override
    public Result updateWork(Work work) {
//        WorkExample example = new WorkExample();
//        WorkExample.Criteria criteria = example.createCriteria();
//
//        // id
//        if (NotNull.judge(work.getWorkId()))
//            criteria.andWorkIdEqualTo(work.getWorkId());
//
//        // 发布时间
//        //Date date = new Date();
//        //work.setReleaseTime(date);
////        if (NotNull.judge(work.getReleaseTime()))
////            criteria.andReleaseTimeEqualTo(work.getReleaseTime());
//
//        // 作业主题
//        if (NotNull.judge(work.getWorkTheme()))
//            criteria.andWorkThemeEqualTo(work.getWorkTheme());
//
//        // 内容
//        if (NotNull.judge(work.getWorkContent()))
//            criteria.andWorkContentEqualTo(work.getWorkContent());
//
//            // 计划完成时间
//        if (NotNull.judge(work.getCompletionTime()))
//            criteria.andCompletionTimeEqualTo(work.getCompletionTime());

        int res = workMapper.updateByPrimaryKeySelective(work);
        if (res > 0) {
            return ResultUtil.success("更新成功", res);
        } else {
            return ResultUtil.error("更新失败");
        }
    }

    @Override
    public Result reply(ReplyWorkReceive replyWorkReceive) {
        return null;
    }

    @Override
    public Result deleteWork(Integer workId) {
        int res = 0;
        boolean rs = true;
        StudentWorkExample studentWorkExample = new StudentWorkExample();
        studentWorkExample.createCriteria().andWorkIdEqualTo(workId);
        //查询学生作业
        List<com.group3.domain.StudentWork> studentWorks = studentWorkMapper.selectByExample(studentWorkExample);
        for (com.group3.domain.StudentWork studentWork1 : studentWorks) {
            //        没有打分时 得分为-1  ,
            if (studentWork1.getScore() == -1) {

            } else {
                rs = false;
                break;
            }
        }
//        作业中只要出现一个相同id的作业被打分，就不删除这个作业
        if (rs) {
//            先删除拥有外建的表
            res = studentWorkMapper.deleteByExample(studentWorkExample);
            if (res > 0) {
//                删除主键表
                res = workMapper.deleteByPrimaryKey(workId);
            } else {
                return ResultUtil.error("删除作业操作失败");
            }
        } else {
            return ResultUtil.error("已经打分无法删除");
        }
        return res > 0 ? ResultUtil.success("删除成功") : ResultUtil.error("删除失败");
    }
}
    











